import org.deltaset.support.gen.AbstractGenWriter;
import org.deltaset.support.meta.MetaModelFactory;

public class MenuWriter extends AbstractGenWriter{

    public boolean isSatisfied(){
        return true;
    }
    
    public void write(){
        if(true==getContext().getOverwrite()){
            return;
        }
        def dsonString = getContext().getCommandContext();
        def model = MetaModelFactory.fromDsonString(dsonString, getContext().getPackageName());
        def baseDir = getContext().getBaseDir();
        MenuWriter.write(baseDir,model);
        model.fields.each{f->
            if(!f.fields.isEmpty()){
                MenuWriter.write(baseDir,f);
            }
        }
    }

    static void write(baseDir, model){        
        def fileName = "/src/main/webapp/resources/app/menu.xhtml"
        File menuFile=new File(baseDir,fileName)
        def allLines = menuFile.readLines()
        def changedLines=[]       
        
        allLines.each{line ->
            if(line.contains("</app:menu-form>")){
                changedLines.add("    <app:menu-group groupName=\"ADDED ${model.typeClassLike}\">")                
                /*
                if(model.hasChildFields()){
                    changedLines.add("        <app:menu-item itemOutcome=\"/secured/${model.typeBeanLike}/list\" itemValue=\"#{${model.typeBeanLike}Msg[\'view.title\']}\"/>")                
                }else{*/
                    changedLines.add("        <app:menu-item itemOutcome=\"/secured/${model.typeBeanLike}/#{deltasetConfig['viewType']}\" itemValue=\"#{${model.typeBeanLike}Msg[\'view.title\']}\"/>")
                //}
                
                changedLines.add("    </app:menu-group>")
            }
            changedLines.add(line)
        }
        menuFile.withWriter{file ->
            changedLines.each{line ->
                file.writeLine(line)
            }
        }
    }
}